﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml;

namespace GpxTrackSplit
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: GpxTrackSplit.exe <SourceFile.gpx> [<OutputFolder>]");
                return;
            }
            var outputFolder = "";
            if (args.Length > 1)
            {
                outputFolder = args[1];
                if (!Directory.Exists(outputFolder))
                {
                    Directory.CreateDirectory(outputFolder);
                }
            }
            var sourceName = args[0];
            if (!File.Exists(sourceName))
            {
                Console.WriteLine("Specified source file not found.");
                return;
            }
            var doc = new XmlDocument();
            doc.Load(sourceName);
            var trackNodes = doc.GetElementsByTagName("trk");
            foreach (XmlNode trackNode in trackNodes)
            {
                var fullPath = Path.Combine(outputFolder, GetTrackFileName(trackNode));
                var writer = XmlWriter.Create(fullPath);
                writer.WriteStartDocument();
                writer.WriteStartElement("gpx", "http://www.topografix.com/GPX/1/1");
                writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
                writer.WriteAttributeString("xsi", "schemaLocation", null, "http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd");
                writer.WriteAttributeString("creator", "GpxTrackSplit http://rysenko.com/");
                writer.WriteAttributeString("version", "1.1");
                writer.WriteRaw(trackNode.OuterXml);
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Close();
            }
        }

        static string GetTrackFileName(XmlNode node)
        {
            var trackName = "Undefined";
            foreach (XmlNode childNode in node.ChildNodes)
            {
                if (childNode.Name.ToLowerInvariant() == "name")
                {
                    trackName = childNode.InnerText;
                    break;
                }
            }
            foreach (var invalidChar in Path.GetInvalidFileNameChars())
            {
                trackName = trackName.Replace(invalidChar.ToString(CultureInfo.InvariantCulture), "");
            }
            return trackName + ".gpx";
        }
    }
}
